package com.scalar.chiptrack.adaptor.sitime.utac;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FTPConnectMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 16 Apr, 2010
 * Time: 7:08:50 PM
 * To change this template use File | Settings | File Templates.
 */
public class UTACFTPAdaptor extends JobHandler implements AdaptorConstants
{

    private static final int    PORT            = 21;
    private static final String FTP_HOST        = "ftp.sitime.net";
    public  static final String ADAPTOR_NAME    = "UTAC_FTP";
    public static final String FILE_NAME_TRANSACTION = "TRANS";
    public static final String FILE_NAME_SHIP   = "SHIP";

    private String m_username           = null;
    private String m_password           = null;
    private Logger m_adaptorLogger      = null;
    private String m_dataOutputDir      = null;
    private int    m_adaptor_id         = -1;
    private int    m_adaptor_id1        = -1;
    private String fileDate             = null;
    private String fileDate1             = null;

    public UTACFTPAdaptor() throws Exception
    {

        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation(VENDOR_NAME_UTAC, WIP_TYPE_TEST );

            m_username = vendorAdaptor.getUserId();
            m_password = vendorAdaptor.getPassWord();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory();

            if (m_dataOutputDir != null)
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
            }

            AdaptorUtils.makeAllAdaptorDirs(m_dataOutputDir);
            m_adaptorLogger = AdaptorUtils.getAdaptorLogger(m_dataOutputDir, VENDOR_NAME_UTAC);
            AdaptorUtils.setLogger( m_adaptorLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading UTAC FTP Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }
    }

    public static void main( String[] args ) throws Exception
    {
        new UTACFTPAdaptor().execute();
    }

    public void execute() throws Exception
    {
        java.util.Date begDate = null;
        try
        {
            //Getting the last Run Adaptor file Date ( As we are Inserting in the new Adaptor run info in the Starting itself)
            fileDate   = AdaptorRunInfo.getAdaptorLastParsedFileDate( ADAPTOR_NAME );
            fileDate1   = AdaptorRunInfo.getAdaptorLastParsedFileDate( "UTAC_FTP_SHIP" );

            //When File Date is NULL Setting the File Date Back to 4 Days From Current Date
            if ( fileDate == null )
            {
            	Calendar cal = Calendar.getInstance();
                cal.add( Calendar.DAY_OF_MONTH, -3 );
                begDate = cal.getTime();
                fileDate = StringUtils.formatDateToString( begDate, "MM/dd/yyyy");
            }
            if ( fileDate1 == null )
            {
            	Calendar cal = Calendar.getInstance();
                cal.add( Calendar.DAY_OF_MONTH, -3 );
                begDate = cal.getTime();
                fileDate1 = StringUtils.formatDateToString( begDate, "MM/dd/yyyy");
            }

            //System.out.println("fileDate = " + fileDate);
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
            m_adaptor_id1 = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, "UTAC_FTP_SHIP", CONSTANT_SUCCESS, -1);

            //Print the header details
            AdaptorUtils.printHeader(VENDOR_NAME_UTAC + " FTP", CONSTANT_ADAPTOR);

            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

            FTPClient ftp = login( FTP_HOST, PORT, m_username, m_password );
            log( "Successfully logged in to " + FTP_HOST );
            System.out.println( "Successfully logged in to " + FTP_HOST );

            //ftp.chdir("/WIP_report");

            //To Down DownLoad the File To Local System at Specepied path
            //downloadTransactionFiles( ftp );
            //ftp.chdir("../");
            System.out.println("Remote directory changed to Root Directory ");
            log("Remote directory changed to Root Directory ");
            ftp.chdir("/Shipment_report");

            downloadShippingFiles( ftp );
            // Log out
            logout( ftp );
            log( "\nSuccessfully logged out from UTAC Ftp Site" );
            System.out.println( "\nSuccessfully logged out from UTAC FTP Site" );
        }
        catch ( Exception e )
        {
            //ReLogin
            try
            {
                AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger);
            }
            catch(Exception ew)
            {
                AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
                AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id1 );

            }
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id1 );
            System.out.println("Exception while trying to connect and read data from "+FTP_HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }
    /**
     *
     * @param host
     * @param port
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    private FTPClient login( String host, int port, String username, String password ) throws Exception
    {
        FTPClient ftp = new FTPClient( host, port );
        ftp.login( username, password );
        ftp.debugResponses( false );
        ftp.setType( FTPTransferType.BINARY );
        // active does not allows me connect to ftp site even any proxy lies in path.
        ftp.setConnectMode( FTPConnectMode.PASV );
        return ftp;
    }

    private void downloadTransactionFiles( FTPClient ftp ) throws Exception
   	{
	   String[] listings = ftp.dir();

       if ( ( listings == null ) || ( listings.length == 0 ) )
       {
           return;
       }
        File file = null;
        byte[] buf = null;
        String tempFileName     = null;
        Date tempFileDate		= null;
        Date tempmaxDate  		= null;
        FileOutputStream fileOutputStream = null;

        System.out.println("\t\n Downloading the Transaction files...... " );
        try
        {
            for ( int i = 0; i < listings.length; i++ )
            {
                if ( listings[i].startsWith( FILE_NAME_TRANSACTION ) )
                {
                    java.util.Date date1 = StringUtils.format( fileDate);
                    java.util.Date date2 = ftp.modtime( listings[i] );

                    if ( date2.compareTo( date1 ) >= 0 )
                    {
                        tempFileDate = date2;
                        if ( tempmaxDate == null )
                        {
                            tempmaxDate = tempFileDate;
                        }
                        else
                        {
                            if ( tempFileDate.compareTo( tempmaxDate ) > 0 )
                            {
                                tempmaxDate = tempFileDate;
                            }
                        }
                        tempFileName = listings[i];
                    }
                }
                if ( fileDate != null && tempFileName != null )
                {
                    log( "\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... " );
                    if ( m_adaptor_id > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , tempFileName.substring(0, tempFileName.indexOf(".") ), FILE_EXTN_CSV, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
                    }
                    buf = ftp.get( tempFileName );
                    fileOutputStream = new FileOutputStream( m_dataOutputDir + "/" + tempFileName, false );
                    fileOutputStream.write( buf );
                    fileOutputStream.flush();
                    tempFileName = null;
                }
            }

            if ( tempmaxDate != null )
            {
                //To Save the Last Modified date from ftp server
                String maxfileDate = StringUtils.formatDateToString( tempmaxDate,"MM/dd/yyyy");
                log( "maxfileDate = " + maxfileDate );
                AdaptorRunInfo.updateLastRunFileDate( m_adaptor_id , maxfileDate );
            }
        }
        catch ( Exception e )
        {
            log ("Exception while downloading......... " + e);
            logout( ftp );
            throw e;
        }

        finally
        {
            if ( fileOutputStream != null )
            {
                try
                {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                catch ( IOException ignore )
                {
                }
           }
       }
   }

    private void downloadShippingFiles( FTPClient ftp ) throws Exception
   	{
	   String[] listings = ftp.dir();

       if ( ( listings == null ) || ( listings.length == 0 ) )
       {
           return;
       }

        byte[] buf = null;
        String tempFileName     = null;
        Date tempFileDate		= null;
        Date tempmaxDate  		= null;
        FileOutputStream fileOutputStream = null;

        System.out.println("\t\n Downloading the Transaction files...... " );
        try
        {
            for ( int i = 0; i < listings.length; i++ )
            {
                if ( listings[i].startsWith( FILE_NAME_SHIP ) )
                {
                    java.util.Date date1 = StringUtils.format( fileDate1);
                    java.util.Date date2 = ftp.modtime( listings[i] );

                    if ( date2.compareTo( date1 ) >= 0 )
                    {
                        tempFileDate = date2;
                        if ( tempmaxDate == null )
                        {
                            tempmaxDate = tempFileDate;
                        }
                        else
                        {
                            if ( tempFileDate.compareTo( tempmaxDate ) > 0 )
                            {
                                tempmaxDate = tempFileDate;
                            }
                        }
                        tempFileName = listings[i];
                    }
                }
                if ( fileDate != null && tempFileName != null )
                {
                    log( "\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... " );
                    //for shwing which files are parsed using same adaptorID
                    if ( m_adaptor_id > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , tempFileName.substring(0, tempFileName.indexOf(".") ), FILE_EXTN_CSV, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
                    }
                    buf = ftp.get( tempFileName );
                    fileOutputStream = new FileOutputStream( m_dataOutputDir + "/" + tempFileName, false );
                    fileOutputStream.write( buf );
                    fileOutputStream.flush();
                    tempFileName = null;
                }
            }

            if ( tempmaxDate != null )
            {
                //To Save the Last Modified date from ftp server
                String maxfileDate = StringUtils.formatDateToString( tempmaxDate,"MM/dd/yyyy");
                log( "maxfileDate = " + maxfileDate );
                AdaptorRunInfo.updateLastRunFileDate( m_adaptor_id1 , maxfileDate );
            }
        }
        catch ( Exception e )
        {
            log ("Exception while downloading......... " + e);
            logout( ftp );
            throw e;
        }

        finally
        {
            if ( fileOutputStream != null )
            {
                try
                {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                catch ( IOException ignore )
                {
                }
           }
       }
   }

    private void logout( FTPClient ftp ) throws Exception
    {
        if ( ftp == null )
        {
            return;
        }
        try
        {
            ftp.quit();
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From UTAC FTP Site" + ignore );
            throw ignore;
        }
        ftp = null;
    }

    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}

